package com.thinkgem.jeesite.modules.euler.sdk;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.springframework.beans.factory.annotation.Autowired;

import com.thinkgem.jeesite.modules.euler.sdk.base.Command;
import com.thinkgem.jeesite.modules.euler.sdk.cmd.MonitorBegin;

public class CommandFactory {

	static Map<String, Option> optionNames = new HashMap<String, Option>();
	static Map<String, Command> cmdMap = new HashMap<String, Command>();
	static CommandLine cmd;
	static String TYPE = "type";
	public static String CMD_NAME = "name";
	List<Command> cmdList;

	void registerAllCmd() {
		for (Command cmd : cmdList) {
			if (cmd != null) {
				cmdMap.put(cmd.getName(), cmd);
			}
		}
	}

	static Command getCmd(String name) {
		return cmdMap.get(name);
	}

	void initCommandLine(String[] args) throws Throwable {
		Options options = new Options();
		options.addOption(TYPE, true, TYPE);
		options.addOption(CMD_NAME, true, CMD_NAME);

		for (Command c : cmdMap.values()) {
			c.addOptions(options);
		}

		CommandLineParser parser = new PosixParser();
		cmd = parser.parse(options, args);
	}

	public static String getCmdName() {
		if (cmd.hasOption(TYPE)) {
			return cmd.getOptionValue(TYPE);
		}
		return null;
	}

	public void executeCommand() {
		Command command = CommandFactory.getCmd(CommandFactory.getCmdName());
		if (command == null) {
			return;
		}
		command.execute(cmd);
	}

	public List<Command> getCmdList() {
		return cmdList;
	}

	public void setCmdList(List<Command> cmdList) {
		this.cmdList = cmdList;
	}
}
